package com.academico.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.academico.database.Connect;
import com.academico.model.Disciplina;

public class DisciplinaDAO {
	
	private Connection connection;

	public DisciplinaDAO() {
		this.connection = Connect.getInstance();;
	}
	
	public void update(Disciplina disciplina){
		String query = "UPDATE disciplina SET situacao = '"+ disciplina.getSituacaoDisciplina() +
			"' where codigodisciplina = " + disciplina.getCodigoDisciplina();
		System.out.println(query);
			Statement stmt = null; 
		try {
			stmt = connection.createStatement();
			stmt.executeUpdate(query);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}	
		}
	}
	
	public List<Disciplina> findAll(){
		String query = "SELECT * FROM disciplina";
		
		System.out.println(query);
		Statement stmt = null; 
		List<Disciplina> listaDisciplina = new ArrayList<Disciplina>();
		try {
			stmt = connection.createStatement();
			ResultSet rs = stmt.executeQuery(query);
			
			while (rs.next()) {
				Disciplina disciplina = new Disciplina();
				disciplina.setCodigoDisciplina(rs.getInt("codigodisciplina"));
				disciplina.setCodigoCurso(rs.getInt("codigocurso"));
				disciplina.setDescricao(rs.getString("descricao"));
				disciplina.setDataCriacao(rs.getDate("datacriacao"));
				disciplina.setCargaHoraria(rs.getInt("cargahoraria"));
				disciplina.setSituacaoDisciplina((Disciplina.SituacaoDisciplina.valueOf(rs.getString("situacao"))));
				
				listaDisciplina.add(disciplina);
			}
			return listaDisciplina;
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	public void save(Disciplina disciplina){
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy/MM/dd");
		String query = "INSERT INTO disciplina (codigodisciplina, codigocurso, descricao, datacriacao, cargahoraria, situacao)";
		query += "VALUES ('"+ disciplina.getCodigoDisciplina() + 
			"','" + disciplina.getCodigoCurso() + 
			"','" + disciplina.getDescricao() + 
			"','" + sfd.format(disciplina.getDataCriacao()) + 
			"','" + disciplina.getCargaHoraria() + 
			"','" + disciplina.getSituacaoDisciplina() + "')";
		
		System.out.println(query);
		
			Statement stmt = null; 
		try {
			stmt = connection.createStatement();
			stmt.executeUpdate(query);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}	
		}
		
	}
	

}
